﻿using Questionary.Logic;
using Questionary.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Questionary.Views
{
    public partial class QuestionManager : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
			if(!IsPostBack)
				LoadData();
        }

		private void LoadData()
		{
			List<QuestionItem> questions = FileHelper.GetObject<List<QuestionItem>>(Request.MapPath(FilePaths.QuestionFilePath));
			rptQuestions.DataSource = questions;
			rptQuestions.DataBind();
		}

		protected void rptQuestions_ItemCommand(object source, RepeaterCommandEventArgs e)
		{
			Label dataLabel = (Label)e.Item.FindControl("aId");

			int adId = 0;
			if (dataLabel != null)
			{
				int.TryParse(dataLabel.Text, out adId);
			}

			if (e.CommandName == "DelCmd")
			{
				List<QuestionItem> questions = FileHelper.GetObject<List<QuestionItem>>(Request.MapPath(FilePaths.QuestionFilePath));
				QuestionItem qItem = null;

				foreach (var item in questions)
				{
					if(item.ID == adId)
					{
						qItem = item;
					}
				}

				if(qItem!= null)
				{
					questions.Remove(qItem);

					var orderList = questions.OrderBy(tmp => tmp.ID).ToList();
					foreach (var item in questions)
					{
						item.ID = orderList.IndexOf(item) + 1;
					}
					FileHelper.WriteObject<List<QuestionItem>>(orderList, Request.MapPath(FilePaths.QuestionFilePath));
				}

				Response.Redirect("QuestionManager.aspx");
			}
		}
	}
}